# -*- encoding: utf-8 -*-
from odoo import api, fields, models, tools,_
from odoo.exceptions import Warning, UserError


class StockReturnPicking(models.TransientModel):
    _inherit = "stock.return.picking"

    @api.multi
    def _create_returns(self):
        print self.env.context.get('active_id')
        Quant = self.env['stock.quant']
        move_dest_exists = False
        product_return_moves = []
        picking = self.env['stock.picking'].browse(
            self.env.context.get('active_id'))
        if picking:
            if picking.state != 'done':
                raise UserError(_("You may only return Done pickings"))
            for move in picking.move_lines:
                if move.scrapped:
                    continue
                if move.move_dest_id:
                    move_dest_exists = True
                # Sum the quants in that location that can be returned (they should have been moved by the moves that were included in the returned picking)
                quantity = sum(quant.qty for quant in Quant.search([
                    ('history_ids', 'in', move.id),
                    ('qty', '>', 0.0),
                    ('location_id', 'child_of', move.location_dest_id.id)
                ]).filtered(
                    lambda
                        quant: not quant.reservation_id or quant.reservation_id.origin_returned_move_id != move)
                               )
                print quantity
                print '------------------------------'
                quantity = move.product_id.uom_id._compute_quantity(quantity,
                                                                    move.product_uom)
                print quantity
                print move.id
                print move.product_id.id
                print '------------------------------'
                for mv_wd in self:
                    for rcd in mv_wd.product_return_moves:
                        print rcd.move_id.id,rcd.quantity,rcd.product_id.id
                        if move.id==rcd.move_id.id and move.product_id.id==rcd.product_id.id and (quantity < rcd.quantity):
                            raise UserError(u'退货数量上限不能超过原单据数量!')

                # product_return_moves.append((0, 0,
                #                              {'product_id': move.product_id.id,
                #                               'quantity': quantity,
                #                               'move_id': move.id}))
        # for move in self:
        #     for rcd in move.product_return_moves:
        #         print rcd.move_id,rcd.quantity
        # if 2>1:
        #     raise UserError(u'退货数量上限不能超过原单据数量!')
        # print '3333'
        new_picking_id, pick_type_id = super(StockReturnPicking,
                                             self)._create_returns()
        return new_picking_id, pick_type_id
        # raise UserError(u'XXXX!')
        # return
